<template>
	<view>
		<view class="roww rowsa border_bottom">
			<view
				:class="{
					ktd: menuType == 1,
					ktd1: menuType == 2
				}"
				class="p-all-20"
				@click="menuTypeClick(1)"
			>
				空退单信息
			</view>
			<view
				class="p-all-20"
				:class="{
					ktd1: menuType == 1,
					ktd: menuType == 2
				}"
				@click="menuTypeClick(2)"
			>
				拒收单信息
			</view>
		</view>
		
		<view class="p-all-25 roww center_center" style="color: red" v-if="menuType == 2">
			<view @click.stop="gAlertClick()">添加异常商品</view>
		</view>
		
		<view class="colonn" v-if="menuType == 1">
			<view class="colonn background1  w-750 p-all-25 m-bottom-20" 
			v-for="(item, index) in gooding"
			v-if="item.chayiIs==2"
			style="border-bottom: 1rpx solid red;"
			>
				<view class="roww">
					<view class="w-710">商品名称：{{ item.goodsName }}</view>
				</view>
				<view class="h-20"></view>
				<view class="roww">
					<view>商品条形码：{{ item.barcode }}</view>
				</view>
				<view class="h-20"></view>
				<view class="roww">
					<view>本次发货数量：{{ item.deliverNum }}/{{ item.unitName }}</view>
				</view>
				<view class="h-20"></view>
				<view class="roww">
					<view>实际到货数量：{{ item.sjNum }}/{{ item.unitName }}</view>
				</view>
				<view class="h-20"></view>
				<view class="roww center_center"
				:style="{
					'color':item.chayi < 0?'red':''
				}"
				>
					<view>需空退数量：：{{ item.chayi }}/{{ item.unitName }}</view>
					<view class="allline"></view>
				</view>
				<view class="h-20"></view>
				<view class="colonn">
					
					<picker :range="wentiList1"
					@change="wentiSel($event,index,1)"
					>
						<view class="roww center_center"
						>
							<view class="w-500" v-if="item.selTxtKt&&item.selTxtKt!=''">到货问题：{{item.selTxtKt}}</view>
							<view class="w-500" v-else >到货问题：<span style="color: red;">请选择</span></view>
							<view class="allline"></view>
							<image src="/static/youjiantou1.png" class="w-40 h-40"></image>
						</view>
					</picker>
					
					<view class="h-20"></view>
					<view>问题补充</view>
					<view class="h-20"></view>
					<view class="w-700 h-300"
					style="border:1px solid #c9c9c9;padding:20rpx;"
					>
						<textarea class="w-660 h-260 "
						v-model="item.reasonKt"
						>
						</textarea>
					</view>
				</view>
				
				<view class="h-25"></view>
				<view class="colonn">
					<view>上传图片</view>
					<view class="h-20"></view>
					<view class="w-700  huanhang"
					>
						<image class="pore  br-25 w-190 h-190 center_center colonn" 
						style="border:2px solid #bababa;" :src="item.imgKt" mode="aspectFill"
						@click.stop="selImg(item,index,1)" v-if="item.imgKt&&item.imgKt!=''"
						>
						</image>
						<view class="pore  br-25 w-190 h-190 center_center colonn"
						style="border:2px solid #bababa;"
						@click.stop="selImg(item,index,1)" v-else
						>
							<image src="/static/shangcau.png" class="w-50 h-50"></image>
						</view>
						
					</view>
				</view>
				
			</view>
		</view>
		
		
		
		<view class="colonn" v-if="menuType == 2">
			<view class="colonn background1 w-750 p-all-25 m-bottom-20" 
			v-for="(item, index) in gooding"
			v-if="item.posunIs==2"
			style="border-bottom: 1rpx solid red;"
			>
				<view class="roww">
					<view class="w-710">商品名称：{{ item.goodsName }}</view>
				</view>
				<view class="h-20"></view>
				<view class="roww">
					<view>商品条形码：{{ item.barcode }}</view>
				</view>
				<view class="h-20"></view>
				<view class="roww">
					<view>本次发货数量：{{ item.deliverNum }}/{{ item.unitName }}</view>
				</view>
				<view class="h-20"></view>
				<view class="roww">
					<view>实际到货数量：{{ item.sjNum }}/{{ item.unitName }}</view>
				</view>
				<view class="h-20"></view>
				
				
				<view class="roww center_center">
					<view class="roww center_center">
						<view>异常数：</view>
						<view style="border: 1px solid #f5f5f5; padding: 0rpx 20rpx">
							<input
								v-model="item.posunnum"
								class="w-200"
								@input="refshCount"
								style="color: red; font-weight: bold; text-align: center; height: 100rpx; font-size: 35rpx"
								placeholder="请输入数量"
							/>
						</view>
						<view class="w-20"></view>
						<view>{{ item.unitName }}</view>
						<view class="allline"></view>
					</view>
					<view class="allline"></view>
					<view @click.stop="todel(index)"
					style="color: red;"
					>点击删除</view>
				</view>
				
				
				<view class="colonn">
					
					<view class="h-20"></view>
					<picker :range="wentiList"
					@change="wentiSel($event,index,2)"
					>
						<view class="roww center_center"
						>
							<view class="w-500" v-if="item.selTxtPs&&item.selTxtPs!=''">到货问题：{{item.selTxtPs}}</view>
							<view class="w-500" v-else >到货问题：<span style="color: red;">请选择</span></view>
							<view class="allline"></view>
							<image src="/static/youjiantou1.png" class="w-40 h-40"></image>
						</view>
					</picker>
					<view class="h-20"></view>
					<view>问题补充</view>
					<view class="h-20"></view>
					<view class="w-700 h-300"
					style="border:1px solid #c9c9c9;padding:20rpx;"
					>
						<textarea class="w-660 h-260 "
						v-model="item.reasonPs"
						>
						</textarea>
					</view>
				</view>
				<view class="h-25"></view>
				<view class="colonn">
					<view>上传图片</view>
					<view class="h-20"></view>
					<view class="w-700  huanhang"
					>
					
						<image class="pore  br-25 w-190 h-190 center_center colonn" 
						style="border:2px solid #bababa;" :src="item.imgPs" mode="aspectFill"
						@click.stop="selImg(item,index,2)" v-if="item.imgPs!=''"
						>
						</image>
						<view class="pore  br-25 w-190 h-190 center_center colonn"
						style="border:2px solid #bababa;"
						@click.stop="selImg(item,index,2)" v-else
						>
							<image src="/static/shangcau.png" class="w-50 h-50"></image>
						</view>
					</view>
				</view>
				
				
			</view>
		</view>

		
		<view class="huuibeijing" v-if="gAlert" style="z-index: 3000;">
			<view class="colonn ppss center_center">
				<image src="/static/guannn.png" @click.stop="gAlertClick" class="w-55 h-55"></image>
				<view class="h-25"></view>
				<view class="colonn tuidanOrderview center_center">
					<view class="h-100" style="line-height: 100rpx">商品列表</view>
					<scroll-view class="w-750 h-500" scroll-y>
						<view class="colonn">
								<view class="roww border_bottom p-all-25" 
								v-for="(item1, index1) in gooding"
								v-if="item1.chayiIs==2"
								@click.stop="addposunList(index1)"
								>
									<view class="w-570 fs-32">
										{{ item1.goodsName }}
									</view>
									<view class="fw-600" style="color: red"  v-if="item1.posunIs==2"
									>取消选择</view>
									<view class="fw-600" style="color: red"  v-if="item1.posunIs==1"
									>点击选择</view>
								</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		
		<view class="roww center_center">
			<view class="btnktd" @click.stop="toReturn">提交空退单和拒收单</view>
		</view>
		<view  class="h-180"></view>
		
	</view>
</template>

<script>
import Compressor from 'compressorjs';
export default {
	
	
	
	data() {
		return {
			gAlert: false,
			menuType: 1,
			gooding: [],
			ordering: [],
			// 问题列表
			wentiList:[
				// '仓库发货问题-漏发',
				// '仓库发货问题-多发',
				'仓库发货问题-错发产品',
				'包装问题-包装破损',
				'包装问题-包装变形',
				'包装问题-包装不一致',
				'包装问题-包装漏气',
				'包装问题-包装涨袋',
				'包装问题-包装脏污',
				'包装问题-包装上的标签信息错误',
				'包装问题-包装袋上无生产日期',
				'包装问题-包装做工不好',
				'包装问题-包装袋上无标签信息',
				'品质问题-产品变质发臭',
				'品质问题-产品发霉',
				'品质问题-产品内有异物',
				'品质问题-产品破损，变形',
				'品质问题-产品缺失（比如少配件空件）',
				'品质问题-生虫',
				'效期问题-效期过半',
				'仓库发货问题-礼盒袋漏发',
				'仓库发货问题-效期倒灌',
			],
			
			wentiList1:[
				'仓库发货问题-漏发',
			],
			
		};
	},
	onLoad() {
		this.gooding = uni.getStorageSync('gooding');
		this.ordering = uni.getStorageSync('ordering');
		this.countGood();
	},
	methods: {
		
		removeDate(){
			uni.removeStorageSync('orderInfo_tiaoxingma');
			uni.removeStorageSync('orderInfo_scanInfo');
			uni.removeStorageSync('orderInfo_orderInfo');
			uni.removeStorageSync('orderInfo_oorder');
			uni.removeStorageSync('orderInfo_goodList');
		},
		
		wentiSel(res,index,type){
			
			console.log(res.detail.value,index,type)
			if(type==1){
				var txt=this.wentiList1[parseInt(res.detail.value)]
			}else{
				var txt=this.wentiList[parseInt(res.detail.value)]
			}
			
			if(type==1){
				this.gooding[index].selTxtKt=txt;
			}else if(type==2){
				this.gooding[index].selTxtPs=txt;
			}
		},
		
		
		blobToFileData(blob) {
		  return new Promise((resolve) => {
		    const reader = new FileReader();
		    reader.onload = (e) => {
		      resolve({
		        path: e.target.result, // 这是可用于 uploadFile 的 DataURL
		        file: new File([blob], 'image.jpg', { type: blob.type })
		      });
		    };
		    reader.readAsDataURL(blob);
		  });
		},

		
		selImg(item,index,type){
			// 使用示例
			uni.chooseImage({
			  count: 1,
			  success: async (res) => {
			    // H5平台获取File对象
			    const file = res.tempFiles[0]; 
			    
			    try {
			      // 使用compressorjs压缩
			      new Compressor(file, {
			        quality: 0.6,
			        maxWidth: 800,
			        maxHeight: 800,
			        success:async(compressedBlob)=> {
			          // 转换Blob为可用路径
			          const fileData = await this.blobToFileData(compressedBlob);
			          
					  uni.showLoading({
					  	title:"图片上传中",
						mask:true
					  })
					  
			          // 上传文件
			          uni.uploadFile({
			            url: 'https://scrm.zuixiyu.com/flask'+'/api/upload',
			            filePath: fileData.path, // 使用转换后的路径
			            name: 'file',
			            formData: {
			              // 可以添加其他表单数据
			            },
			            success: (uploadRes) => {
			              console.log('上传成功', uploadRes.data);
						  var data=JSON.parse(uploadRes.data);
						  console.log("aa",data)
						  this.showimg11(data.path,index,type)
			            },
			            fail: (err) => {
			              console.error('上传失败', err);
			            },
						complete: (res) => {
							uni.hideLoading()
						}
			          });
			        },
			        error(err) {
			          console.error('压缩失败:', err);
			        }
			      });
			    } catch (error) {
			      console.error('处理失败:', error);
			    }
			  }
			});
		},
		
		
		// // 选择图片
		// selImg(item,index,type) {
		// 	uni.chooseImage({
		// 		count: 1, //默认9
		// 		sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
		// 		sourceType: ['camera '], //从相册选择
		// 		success: (res) => {
		// 			console.log(JSON.stringify(res.tempFilePaths));
		// 			if (res.tempFilePaths.length > 0) {
						
		// 				 this.uploadFileImg( res.tempFilePaths[0], item,index,type  );
		// 				// uni.chooseImage({
		// 				//   count: 1,
		// 				//   success: async (res11) => {
		// 				//     const tempFilePaths = res11.tempFilePaths;
		// 				//     // 使用 uni.compressImage 压缩图片
		// 				//     const compressed = await uni.compressImage({
		// 				//       src: tempFilePaths[0],
		// 				//       quality: 70, // 压缩质量
		// 				//       width: '800', // 限制宽度
		// 				//       height: '800' // 限制高度
		// 				//     });
		// 				//     // 上传压缩后的图片
						   
		// 				//   }
		// 				// });
						
						
						
		// 			}
		// 		}
		// 	});
		// },
		// uploadFileImg(img,item,index,type){
		// 	this.toimg(img,item,index,type);
		// },
		// // 上传截图
		// toimg(url, item,index,type) {
		// 	uni.showLoading({
		// 		title:"上传中"
		// 	})
		// 	var data = {
		// 		'file': url
		// 	}
		// 	this.$axios
		// 		.axiosUpload(this.$paths.uploadapi, url, data)
		// 		.then((res) => {
		// 			if (res.code == 200) {
		// 				console.log(res.path)
		// 				this.$tools.showToast("上传完成");
		// 				this.showimg11(res.path,index,type);
		// 			} else {
		// 				this.$tools.showToast(res.msg);
		// 			}
		// 		})
		// 		.catch((err) => {
		// 			console.log('错误回调', err);
		// 		});
		// },
		showimg11(img,index,type) {
			console.log(img,index)
			img=img.split('/');
			img='https://scrm.zuixiyu.com/fileUpload/pd/'+img[img.length-1]
			if (type==1){
				this.gooding[index].imgKt=img;
			}else if (type==2){
				this.gooding[index].imgPs=img;
			}
			
			this.$forceUpdate()
		},
		todel(index){
			console.log(this.gooding[index].posunIs)
			this.gooding[index].posunIs=this.gooding[index].posunIs==1?2:1;
			this.gooding[index].posunnum=0;
			this.refshCount()
			this.$forceUpdate()
		},
		
		toSUbmit(){
			if(!this.isSubmit()){
				return false;
			}
			this.getData()
		},
		isSubmit(){
			this.refshCount();
			var gooding = this.gooding;
			var isSUb=true;
			
			for(var a=0;a<gooding.length;a++){
				var all=0;
				const posunnum = Number(gooding[a].posunnum) || 0;
				const sjNum = Number(gooding[a].sjNum) || 0;
				const chayi = Number(gooding[a].chayi) || 0;
				all=posunnum+sjNum+chayi;
				if(chayi<0){
					this.$tools.showToast("空退数量出现负数，提交失败");
					return false;
				}
				if(all!=gooding[a].deliverNum){
					isSUb=false;
				}
			}
			
			
			
			if(!isSUb){
				this.$tools.showToast("发货数量 ≠ 实际到货 + 空退 + 异常数量，请核对后重新提交！");
				return false;
			}
			var zl=true;
			console.log("擦",gooding.length)
			
			var selIs=true;//是否都选了原因
			
			for(var a=0;a<gooding.length;a++){
				console.log(a,gooding[a].chayiIs,gooding[a].posunIs);
				if(gooding[a].chayiIs==2){
					if(gooding[a].imgKt==''||gooding[a].reasonKt==''){
						console.log("==1",gooding[a].imgKt,gooding[a].reasonKt)
						zl=false
						
						break;
					}
					console.log("=1=",gooding[a].selTxtKt)
					if(gooding[a].selTxtKt==''){
						selIs=false;
					}
				}
				
				if(gooding[a].posunIs==2){
					if(gooding[a].posunnum==0){
						console.log("==a==aa==")
						this.$tools.showToast("填写异常数量不能为0");
						return false;
						break;
					}
					if(gooding[a].imgPs==''||gooding[a].reasonPs==''){
						console.log("==2",gooding[a])
						zl=false
						break;
					}
					console.log("=2=",gooding[a].selTxtPs)
					if(gooding[a].selTxtPs==''){
						selIs=false;
					}
				}
			}
			if(!zl){
				this.$tools.showToast("空退单或者拒收单信息存在原因未说明或者图片未上传");
				return false;
			}
			if(!selIs){
				this.$tools.showToast("空退单或到货异常单存在未选择到货问题");
				return false;
			}
			
			
			return true;
		},
		refshCount(){
			var gooding = this.gooding;
			for(var a=0;a<gooding.length;a++){
				const posunnum = Number(gooding[a].posunnum) || 0;
				const sjNum = Number(gooding[a].sjNum) || 0;
				gooding[a].chayi=gooding[a].deliverNum- posunnum-sjNum;
				if(gooding[a].chayi!=0){
					gooding[a].chayiIs=2;
				}else{
					gooding[a].chayiIs=1;
				}
			}
			this.gooding=gooding;
			this.$forceUpdate()
		},
		addposunList(index) {
			var gooding = this.gooding;
			console.log(gooding[index])
			gooding[index].posunIs=gooding[index].posunIs==1?2:1
			if(gooding[index].posunIs==1){
				gooding[index].posunnum=0;
			}
			this.gooding = gooding;
		},
		gAlertClick() {
			this.gAlert = !this.gAlert;
			console.log('aaa', this.gAlert);
		},
		menuTypeClick(index) {
			this.menuType = index;
		},
		// 计算差异单s
		countGood() {
			var chayiGood=[];
			var gooding = this.gooding;
			for (var a = 0; a < gooding.length; a++) {
				if (gooding[a].sjNum < gooding[a].deliverNum) {
					var obg = gooding[a];
					gooding[a].chayi = gooding[a].deliverNum - gooding[a].sjNum-gooding[a].posunnum;
					gooding[a].chayiIs=2;
				}
				console.log('gooding[a].chayiIs',gooding[a].chayiIs)
			}
			this.gooding = gooding;
		},
		// 创建退货单
		getData(){   
			var ordering=uni.getStorageSync("ordering");
			var gooding=this.gooding;
			for(var a=0;a<gooding.length;a++){
				if(gooding[a].chayiIs==2){
					gooding[a].chayi=gooding[a].chayi==''?0:gooding[a].chayi
				}
				if(gooding[a].posunIs==2){
					gooding[a].posunnum=gooding[a].posunnum==''?0:gooding[a].posunnum
				}
				
			}
			var data={  
				'ordering':ordering,
				'gooding':gooding,
				'userInfowxuserName':uni.getStorageSync("userInfowx")['user']['userName']
			}
			
			
			
			
			this.$axios
				.axios('post', this.$paths.addReturnOrder, data)
				.then((res) => {
					if (res.code == 200) {
						this.removeDate()
						this.$tools.showToast("提交完成");
						setTimeout(res=>{
							uni.reLaunch({
								url:"/pages/index/index"
							})
						},1000)
					} else {
						this.$tools.showToast(res.msg);
					}
				})
				.catch((err) => {
					console.log('错误回调', err);
				});
			
			
			
			
		},
		toReturn(){
			uni.showModal({
				title: '提示',
				content: '确认要提交吗',
				success:  (res)=> {
					if (res.confirm) {
						this.toSUbmit()
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		
		
		
		
		
	}
};
</script>

<style>
@import url('returnOrder.css');
</style>
